/**
 * 
 */
package instant.mail;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public class AttachActivity extends Activity {
	private static final String IMAGE_PREFIX = "photo-";
	private static final int RC_RECORD_VIDEO = 11;
	private static final int RC_TAKE_PICTURE = 12;
	private static final String SAVED_TEMPFILE = "tempfile";
	
	private static final String TAG = "AttachActivity";
	//private static final String VIDEO_PREFIX = "video-";
	private File tempFile;

	private void doReturn(String path) {
		try {
			Intent i = new Intent();
			i.putExtra(EtalkIntent.EXTRA_URI, path);
			//
			if (Constants.DEBUG_ENABLED) {
				ComponentName ca = getCallingActivity();
				Log.d(TAG, "returning: " + ca  +" path: " + path);
			}
			setResult(RESULT_OK, i);
		} catch (Exception e) {
			setResult(RESULT_CANCELED);
			// TODO
			e.printStackTrace();
		}
		finish();
	}

	private String makePrefix(String prefix) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		return prefix+df.format(new Date());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "onActivityResult resultCode " + resultCode + " data: " + data +" tempFile: " + tempFile);
		}
		setResult(resultCode);
		String path = null;
		if (resultCode == RESULT_CANCELED) {
			if (tempFile != null) {
				tempFile.delete();
			}
		} else if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case RC_TAKE_PICTURE: {
				path = tempFile.getAbsolutePath();
				break;
			}
			case RC_RECORD_VIDEO: {
				Uri uri = (data == null ? null : data.getData());
				if (uri != null) {
					path = Utils.getDataPath(this, uri);
				}
				break;
			}
			default:
				//
			}
		} 
		try {
			finishActivity(requestCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//
		Intent my = getIntent();
		String act = my.getAction();
		//
		if (EtalkIntent.ACTION_PICTURE.equals(act) 
				|| EtalkIntent.ACTION_VIDEO.equals(act)
				) {
			doReturn(path);
		} else if (EtalkIntent.ACTION_PICTURE_COMPOSE.equals(act)
				|| EtalkIntent.ACTION_VIDEO_COMPOSE.equals(act)
				) {
			startEtalkActivity(path);
		} else if (EtalkIntent.ACTION_PICTURE_COMPOSEWITH.equals(act)
				|| EtalkIntent.ACTION_VIDEO_COMPOSEWITH.equals(act)
				) {
			startEmailActivity(path);
		} else {
			//invalid values passed, quit
			setResult(RESULT_CANCELED);
			finish();
		}
	}

//	private void startCamcorderActivity() {
//		try {
//			Intent i = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//			tempFile = Files.getTempFile(VIDEO_PREFIX, ".mpeg");
//			Uri uri = Uri.fromFile(tempFile);
//			i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//			i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
//			//
//			startActivityForResult(i, RC_RECORD_VIDEO);
//		} catch (IOException e) {
//			e.printStackTrace();
//			// toast();
//			setResult(RESULT_CANCELED);
//			finish();
//		}
//	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "onCreate bundle: " + savedInstanceState + " file: " + tempFile);
		}
		if (savedInstanceState == null) {
			String act = getIntent().getAction();
			
			if (Constants.DEBUG_ENABLED) {
				Log.d(TAG, "onCreate new request: " + act);
			}

			//
			if (EtalkIntent.ACTION_PICTURE.equals(act)
					|| EtalkIntent.ACTION_PICTURE_COMPOSE.equals(act)
					|| EtalkIntent.ACTION_PICTURE_COMPOSEWITH.equals(act)
					) {
				startCameraActivity();
			} else if (EtalkIntent.ACTION_VIDEO.equals(act)
					|| EtalkIntent.ACTION_VIDEO_COMPOSE.equals(act)
					|| EtalkIntent.ACTION_VIDEO_COMPOSEWITH.equals(act)
					) {
				startCamcorderActivity();
			} else {
				setResult(RESULT_CANCELED);
				finish();
			}
		} else {
			tempFile = (File) savedInstanceState.getSerializable(SAVED_TEMPFILE);
			
			if (Constants.DEBUG_ENABLED) {
				Log.d(TAG, "onCreate restored: " + tempFile);
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "onSaveInstanceState file: " + tempFile +" outState: " + outState);
		}
		outState.putSerializable(SAVED_TEMPFILE, tempFile);
		//
		super.onSaveInstanceState(outState);
	}

	private void startCamcorderActivity() {
		try {
			Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
			startActivityForResult(intent, RC_RECORD_VIDEO);
		} catch (Exception e) {
			e.printStackTrace();
			// toast();
			setResult(RESULT_CANCELED);
			finish();
		}
	}
	
	private void startCameraActivity() {
		try {
			Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);	
			String prefix = makePrefix(IMAGE_PREFIX);
			File sub = Files.getSubFolder(this, Files.SUB_IMAGE);
			tempFile = Files.getTempFile(sub, prefix, FileFormats.EXT_JPG);
			Uri uri = Uri.fromFile(tempFile);
			//
			if (Constants.DEBUG_ENABLED) {
				Log.d(TAG, "startCameraActivity uri: " + uri);
			}
			//
			i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			//
			startActivityForResult(i, RC_TAKE_PICTURE);
		} catch (Exception e) {
			e.printStackTrace();
			// toast();
			setResult(RESULT_CANCELED);
			finish();
		}
	}
	
	private void startEmailActivity(String path) {
		try {
			if (Constants.DEBUG_ENABLED) {
				Log.d(TAG, "startEmailActivity path: " + path);
			}
			String subj = Preferences.getGreetingSubject(this, "");
			String msg = Preferences.getGreetingBody(this, "");
			Intent my = getIntent();
			String name = my.getStringExtra(EtalkIntent.EXTRA_NAME);
			String to = my.getStringExtra(EtalkIntent.EXTRA_EMAIL);
			MailTemplate.startSendActivity(this, name, to, subj, msg, path, null);
			//
			setResult(RESULT_OK);
		} catch (ActivityNotFoundException e) {
			toast(R.string.msg_noapp, e.getMessage(), Toast.LENGTH_LONG);
			setResult(RESULT_CANCELED);
		} catch (Exception e) {
			toast(R.string.msg_fail, e.getMessage(), Toast.LENGTH_LONG);
			setResult(RESULT_CANCELED);
		}
		finish();
	}

	private void startEtalkActivity(String path) {
		try {
			Intent i = new Intent(this, EtalkActivity.class);
			//forward action & email extras
			Intent my = getIntent();
			i.setAction(my.getAction());
			i.putExtras(my);
			i.putExtra(EtalkIntent.EXTRA_URI, path);
			//
			startActivity(i);
		} catch (Exception e) {
			setResult(RESULT_CANCELED);
			// TODO
			e.printStackTrace();
		}
		finish();
	}

	private void toast(int resId, String arg, int duration) {
		CharSequence text = getString(resId, arg);
		Toast.makeText(this, text, duration).show();
	}
}
